//
//  SortViewController.m
//  shiweiquanjing
//
//  Created by xftt on 14-7-9.
//
//

#import "SortViewController.h"
#import "SortCell.h"
#import "QJViewController.h"
#import "MainViewController.h"

@interface SortViewController ()
{
    BOOL isEdit;
    NSArray *_QJSort;
    NSMutableArray *selectSort;
}

@end

@implementation SortViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [_editButton setTitle:@"检查更新" forState:UIControlStateNormal];
    [_editButton addTarget:self action:@selector(checkUpLoad) forControlEvents:UIControlEventTouchUpInside];
    selectSort = [NSMutableArray array];
    //表格
    _tbSort = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 844, 610)];
    [_tbSort setBackgroundColor:[UIColor colorWithHexString:@"#444444"]];
    [_tbSort setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    UIView *v= [[UIView alloc]initWithFrame:CGRectMake(0, 0, 844, 20)];
    [_tbSort setTableHeaderView:v];
    [_tbSort setDataSource:self];
    [_tbSort setDelegate:self];
    [_contentView addSubview:_tbSort];
    
    //操作菜单
    _optionView = [[UIView alloc] initWithFrame:CGRectMake(0, 610, 844, 88)];
    [_optionView setBackgroundColor:[UIColor colorWithHexString:@"#444444"]];
    [_contentView addSubview:_optionView];
    
    //分割线
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 844, 2)];
    [line setBackgroundColor:[UIColor colorWithHexString:@"#555555"]];
    [_optionView addSubview:line];
    
    //已用方块
    UIView *useView = [[UIView alloc]initWithFrame:CGRectMake(50, 35, 15, 15)];
    [useView setBackgroundColor:[UIColor colorWithHexString:@"#880000"]];
    [_optionView addSubview:useView];
    
    //已用
    UILabel *useMsg = [[UILabel alloc] initWithFrame:CGRectMake(75, 20, 100, 45)];
    [useMsg setTextColor:[UIColor lightTextColor]];
    [useMsg setBackgroundColor:[UIColor clearColor]];
    [useMsg setFont:[UIFont systemFontOfSize:12]];
    [useMsg setText:[self getDiskSpaceInfo:1]];
    [_optionView addSubview:useMsg];
    
    //空闲方块
    UIView *freeView = [[UIView alloc]initWithFrame:CGRectMake(180, 35, 15, 15)];
    [freeView setBackgroundColor:[UIColor colorWithHexString:@"#888888"]];
    [_optionView addSubview:freeView];
    
    //空闲
    UILabel *freeMsg = [[UILabel alloc] initWithFrame:CGRectMake(205, 20, 100, 45)];
    [freeMsg setTextColor:[UIColor lightTextColor]];
    [freeMsg setBackgroundColor:[UIColor clearColor]];
    [freeMsg setFont:[UIFont systemFontOfSize:12]];
    [freeMsg setText:[self getDiskSpaceInfo:2]];
    [_optionView addSubview:freeMsg];
    
    //编辑按钮
    _btnEdit = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btnEdit setFrame:CGRectMake(587, 20, 105, 45)];
    [_btnEdit setTitleColor:[UIColor colorWithHexString:@"#AAAAAA"] forState:UIControlStateNormal];
    [_btnEdit setBackgroundColor:[UIColor colorWithHexString:@"#555555"]];
    [_btnEdit setTitle:@"编辑" forState:UIControlStateNormal];
    [_btnEdit addTarget:self action:@selector(doEdit:) forControlEvents:UIControlEventTouchUpInside];
    [_optionView addSubview:_btnEdit];
    
    //删除按钮
    _btnDel = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btnDel setFrame:CGRectMake(720, 20, 105, 45)];
    [_btnDel setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:UIControlStateNormal];
    [_btnDel setBackgroundColor:[UIColor colorWithHexString:@"#555555"]];
    [_btnDel setTitle:@"删除" forState:UIControlStateNormal];
    [_btnDel addTarget:self action:@selector(doDel:) forControlEvents:UIControlEventTouchUpInside];
    [_optionView addSubview:_btnDel];
}

-(void)viewWillAppear:(BOOL)animated
{
    if (isEdit) {
        [self doEdit:nil];
    }
    else
    {
        [self reloadData];
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [self.view endEditing:YES];
}

-(void)reloadData
{
    [self loadSortList];
    [_tbSort reloadData];
    [selectSort removeAllObjects];

    for (int i = 0; i<[_QJSort count]; i++) {
        SortCell *cell = (SortCell*)[_tbSort cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        [cell setIsSelect:NO];
    }
}

- (void)checkUpLoad
{
    [(MainViewController*)self.navigationController.tabFrameController upLoadDataWithShow:YES];
}

- (void)loadSortList
{
    NSUserDefaults *_Data = [NSUserDefaults standardUserDefaults];
    _QJSort = [_Data objectForKey:@"QJSort"];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (isEdit) {
        return [_QJSort count];
    }
    return [_QJSort count]+1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = @"SortCell";
    if (isEdit) {
        CellIdentifier = @"EditCell";
    }
    
    SortCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(cell == nil)
    {
        cell = [[SortCell alloc] initWithType:isEdit reuseIdentifier:CellIdentifier];
        cell.FController = self;
        if (isEdit) {
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        else
        {
            cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
            cell.selectedBackgroundView.backgroundColor = [UIColor colorWithHexString:@"#4D4D4D"];
        }
    }
    [cell setRow:indexPath.row];
    if (isEdit) {
        [cell setSort:[_QJSort objectAtIndex:indexPath.row]];
    }
    else
    {
        if (indexPath.row>0) {
            [cell setSort:[_QJSort objectAtIndex:indexPath.row-1]];
        }
        else
        {
            NSDictionary *sort = [[NSDictionary alloc] initWithObjects:@[@"未分类全景"] forKeys:@[@"sortname"]];
            [cell setSort:sort];
        }
    }
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (isEdit) {
        SortCell *cell = (SortCell*)[tableView cellForRowAtIndexPath:indexPath];
        [cell setIsSelect:!cell.isSelect];
        if (cell.isSelect) {
            [selectSort addObject:[_QJSort objectAtIndex:indexPath.row]];
        }
        else
        {
            [selectSort removeObject:[_QJSort objectAtIndex:indexPath.row]];
        }
    }
    else
    {
        if (indexPath.row>0) {
            QJViewController *qjview= [[QJViewController alloc]initWithType:3];
            [qjview setSortInfo:[_QJSort objectAtIndex:indexPath.row-1]];
            [self.navigationController pushViewController:qjview animated:YES];
        }
        else
        {
            QJViewController *qjview= [[QJViewController alloc]initWithType:1];
            [self.navigationController pushViewController:qjview animated:YES];
        }
    }
}



-(void)doEdit:(id)sender
{
    isEdit = !isEdit;
    if (isEdit) {
        [_btnEdit setTitle:@"完成" forState:UIControlStateNormal];
        [_btnDel setTitleColor:[UIColor colorWithHexString:@"#AAAAAA"] forState:UIControlStateNormal];
    }
    else
    {
        [_btnEdit setTitle:@"编辑" forState:UIControlStateNormal];
        [_btnDel setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:UIControlStateNormal];
    }
    [_tbSort reloadData];
}

-(void)doDel:(id)sender
{
    if (isEdit) {
        if ([selectSort count]>0) {
            NSUserDefaults *_Data = [NSUserDefaults standardUserDefaults];
            NSArray *_AllQJ = [_Data objectForKey:@"QJData"];
            NSMutableArray *arr = [NSMutableArray arrayWithArray:_QJSort];
            
            BOOL ihas = NO;
            for (id sortDic in selectSort) {
                
                BOOL hasChild = NO;
                NSString *sortid = [sortDic objectForKey:@"sortid"];
                for (int i=0; i<[_AllQJ count]; i++) {
                    if([[[_AllQJ objectAtIndex:i] objectForKey:@"sortid"] isEqualToString:sortid])
                    {
                        hasChild = YES;
                        ihas = YES;
                        break;
                    }
                }
                
                if (!hasChild) {
                    [arr removeObject:sortDic];
                }
            }
            [_Data setObject:arr forKey:@"QJSort"];
            [_Data synchronize];
            [self reloadData];
            if (ihas) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"选中项中部分分类含有全景\n该分类无法删除！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
            }
        }
    }
}

- (void)saveSort
{
    NSUserDefaults *_Data = [NSUserDefaults standardUserDefaults];
    [_Data setValue:_QJSort forKey:@"QJSort"];
    [_Data synchronize];
}
- (void)saveSort:(NSString*)name path:(NSInteger)row
{
    NSUserDefaults *_Data = [NSUserDefaults standardUserDefaults];
    NSMutableArray *temp = [NSMutableArray arrayWithArray:[_Data objectForKey:@"QJSort"]];
    NSMutableDictionary *sort = [NSMutableDictionary dictionary];
    [sort setObject:name forKey:@"sortname"];
    [sort setObject:[[_QJSort objectAtIndex:row] objectForKey:@"sortid"] forKey:@"sortid"];
    [temp removeObjectAtIndex:row];
    [temp insertObject:sort atIndex:row];
    [_Data setObject:temp forKey:@"QJSort"];
    [_Data synchronize];
    [self reloadData];
}

-(NSString *)getDiskSpaceInfo:(int)type{
    uint64_t totalSpace = 0.0f;
    uint64_t totalFreeSpace = 0.0f;
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];
    
    if (dictionary)
    {
        NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
        NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
        totalSpace = [fileSystemSizeInBytes floatValue];
        totalFreeSpace = [freeFileSystemSizeInBytes floatValue];
    }
    else
    {
        return nil;
    }
    NSString *infostr;
    switch (type) {
        case 1:
            infostr = [NSString stringWithFormat:@"已用 %.2f GB", (((totalSpace-totalFreeSpace)/1024.0f)/1024.0f)/1024.0f];
            break;
            
        case 2:
            infostr = [NSString stringWithFormat:@"空闲 %.2f GB", ((totalFreeSpace/1024.0f)/1024.0f)/1024.0f];
            break;
    }
    return infostr;
    
}
@end
